from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response

from apps.login.serializers import LoginSerializers
from apps.login.models import UserInfo

import uuid


# 登录/注册视图
class LoginView(APIView):
    def post(self,request):
        # request.data = {'nickName': '', 'avatarUrl': '','token':''}

        print(f"前端传来的数据：{request.data}")

        ser = LoginSerializers(data=request.data)

        print(f"序列化器验证结果:{ser.is_valid()}")

        if not ser.is_valid():
            return Response({"status":False})

        user_token = ser.validated_data.get("token") # 用户请求时传入的token Unregistered user
        print(f"用户传入的:{user_token}")

        access_token = UserInfo.objects.filter(token=user_token) #从数据库中查询到的token
        print(access_token)
        if not access_token:#如果查询的数据为空，说明是新用户
            # 生成token
            token = generate_token()
            print(f"生成的token:{token}")
            ser.save(token=token)
            return Response({"status":True,"message":"新用户","token":token})
        return Response({"status": False, "message": "老用户", "token": user_token})



# 设计一个方法用于生成微信用户的token
def generate_token():
    token = uuid.uuid4()
    return str(token)